<template>
  <div class="single-roll-analysis">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="入口卷号">
          <el-input v-model="searchForm.entID" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="异常原因">
          <el-input v-model="searchForm.secReason" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="时间">
          <el-date-picker v-model="searchForm.timeRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-panel">
      <el-table :data="allTableData" border style="width: 100%;" height="calc(100vh - 180px)"
        :header-cell-style="{ background: '#2a5caa', color: '#fff', padding: '8px 10px', textAlign: 'center', fontWeight: 'normal', border: 'none' }"
        :cell-style="{ padding: '8px 10px', textAlign: 'center', color: '#c0c4cc', border: 'none' }"
        :row-style="{ background: '#0f2142' }">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="createTime" label="时间" width="160">
          <template #default="scope">
            <span>{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="entID" label="入口卷号" width="160" />
        <el-table-column prop="extID" label="出口卷号" width="160" />
        <el-table-column prop="steelGrade" label="钢牌号" width="110" />
        <el-table-column prop="outMatWidth" label="宽度[mm]" width="90" />
        <el-table-column prop="outMatThk" label="厚度[mm]" width="90" />
        <el-table-column prop="outMatWt" label="重量[kg]" width="90" />
        <el-table-column prop="outputSe" label="计划秒用时" width="90" />
        <el-table-column prop="outputSeActual" label="实际秒用时" width="90" />
        <el-table-column prop="diff" label="实际-计划秒用时" width="120">
          <template #default="scope">
            <span :style="{ color: Number(scope.row.diff) > 0 ? 'red' : '' }">{{ scope.row.diff }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="异常区域" width="120">
          <template #default="scope">
            <el-select v-model="scope.row.type" placeholder="选择区域" size="small" style="width: 100%">
              <el-option label="入口" value="0" />
              <el-option label="轧机" value="1" />
              <el-option label="圆盘剪" value="2" />
              <el-option label="焊接" value="3" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="secReason" label="异常原因" width="240">
          <template #default="scope">
            <div class="ellipsis-cell">
              <el-input v-model="scope.row.secReason" type="textarea" :rows="scope.row._showFullSecReason ? 4 : 1"
                :autosize="scope.row._showFullSecReason ? { minRows: 4, maxRows: 8 } : false" class="ellipsis-input"
                :class="{ 'ellipsis-single': !scope.row._showFullSecReason }" placeholder="请输入异常原因" />
              <span v-if="scope.row.secReason && scope.row.secReason.length > 20" class="expand-btn"
                @click="scope.row._showFullSecReason = !scope.row._showFullSecReason">
                {{ scope.row._showFullSecReason ? '收起' : '...展开' }}
              </span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="crew" label="班次" align="center">
          <template #default="scope">
            <span>{{ scope.row.shift == '1' ? '白' : '夜' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="crew" label="班组" align="center">
          <template #default="scope">
            <span>{{ scope.row.crew == 'A' ? '甲' : scope.row.crew == 'B' ? '乙' : scope.row.crew == 'C' ? '丙' : '丁'
              }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="porNo" label="开卷机" width="100" />
        <el-table-column prop="stopFlag" label="是否停机卷" width="100">
          <template #default="scope">
            <span>{{ scope.row.stopFlag == 1 ? '是' : '否' }}</span>
          </template>

        </el-table-column>
        <el-table-column prop="slowFlag" label="是否降速卷" width="100">
          <template #default="scope">
            <span>{{ scope.row.slowFlag == 1 ? '是' : '否' }}</span>
          </template>


        </el-table-column>

        <el-table-column prop="team" label="生产过程曲线" width="130">
          <template #default="scope">
            <el-button type="primary" size="small" @click.stop="showMore(scope.row)">更多</el-button>
          </template>
        </el-table-column>
        <el-table-column label="入口区域" align="center">
          <el-table-column prop="enHourlyOutputSet" label="理论小时产量[t/h]" width="160" />
          <el-table-column prop="enHourlyOutputReal" label="实际小时产量[t/h]" width="160" />
        </el-table-column>
        <el-table-column label="酸洗区域" align="center">
          <el-table-column prop="pickHourlyOutputSet" label="理论小时产量[t/h]" width="160" />
          <el-table-column prop="pickHourlyOutputReal" label="实际小时产量[t/h]" width="160" />
        </el-table-column>
        <el-table-column label="轧机区域" align="center">
          <el-table-column prop="theoreticalCleaningTime" label="理论时间" width="120" />
          <el-table-column prop="actualCleaningTime" label="实际时间" width="120" />
        </el-table-column>
        <el-table-column label="详情" width="100" fixed="right" align="center">
          <template #default="scope">
            <button class="action-btn submit-btn" @click="selectRow(scope.row)">提交</button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-panel">
      <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" background />
    </div>

    <!-- 添加弹窗组件 -->
    <el-dialog v-model="dialogVisible" :title="'卷号：' + currentCoilNumber" width="90%" class="efficiency-dialog"
      :close-on-click-modal="false" :destroy-on-close="true" @close="handleDialogClose">
      <!-- 时间数据表格 -->
      <!-- <div class="time-data-table">
        <el-text>时间</el-text>
        <el-table
          :data="timeData"
          border
          style="width: 100%"
          :header-cell-style="{ background: '#2a5caa', color: '#fff', textAlign: 'center' }"
          :cell-style="{ textAlign: 'center', color: '#c0c4cc' }"
          :row-style="{ background: '#0f2142' }"
        >
          <el-table-column label="剪切">
            <el-table-column label="实际" prop="shearActual" />
            <el-table-column label="理论" prop="shearTheory" />
          </el-table-column>
          <el-table-column label="移至等待位">
            <el-table-column label="实际" prop="waitActual" />
            <el-table-column label="理论" prop="waitTheory" />
          </el-table-column>
          <el-table-column label="移至焊机">
            <el-table-column label="实际" prop="weldActual" />
            <el-table-column label="理论" prop="weldTheory" />
          </el-table-column>
          <el-table-column label="焊接">
            <el-table-column label="实际" prop="weldingActual" />
            <el-table-column label="理论" prop="weldingTheory" />
          </el-table-column>
          <el-table-column label="焊接完成至冲套">
            <el-table-column label="实际" prop="postWeldActual" />
            <el-table-column label="理论" prop="postWeldTheory" />
          </el-table-column>
          <el-table-column label="冲套">
            <el-table-column label="实际" prop="punchActual" />
            <el-table-column label="理论" prop="punchTheory" />
          </el-table-column>
          <el-table-column label="带尾剪切">
            <el-table-column label="实际" prop="tailShearActual" />
            <el-table-column label="理论" prop="tailShearTheory" />
          </el-table-column>
          <el-table-column label="带尾移至等待位">
            <el-table-column label="实际" prop="tailWaitActual" />
            <el-table-column label="理论" prop="tailWaitTheory" />
          </el-table-column>
        </el-table>
      </div> -->

      <!-- 图表区域 -->
      <div class="charts-container">
        <template v-if="activeView === '轧制'">
          <div class="chart-wrapper">
            <div class="chart-title">入口速度曲线</div>
            <div class="chart" ref="tempChartRef"></div>
          </div>
          <div class="chart-wrapper">
            <div class="chart-title">轧机出口速度曲线</div>
            <div class="chart" ref="outChartRef"></div>
          </div>
          <div class="chart-wrapper">
            <div class="chart-title">工艺速度曲线</div>
            <div class="chart" ref="outputChartRef"></div>
          </div>
        </template>
        <template v-else>
          <div class="chart-wrapper">
            <div class="chart-title">酸洗速度曲线</div>
            <div class="chart" ref="tempChartRef"></div>
          </div>
          <div class="chart-wrapper">
            <div class="chart-title">酸洗温度曲线</div>
            <div class="chart" ref="outputChartRef"></div>
          </div>
        </template>
      </div>

      <!-- 切换按钮 -->

    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed } from 'vue';
import * as echarts from 'echarts';
import { acidRollingApi } from '/@/api/acidRollingProductionEfficiency/index';
import { historyApi } from '/@/api/furnaceTempDynamicCtrl/history';
import { ElMessage } from 'element-plus';

interface TableRow {
  id: number;
  entID: string;
  extID: string;
  steelGrade: string;
  outMatWidth: number;
  outMatThk: number;
  outMatWt: string;
  porNo: string;
  shift: string;
  crew: string;
  prodStartTime: string;
  enSpeedAvg: number;
  enSpeedSet: number;
  pickSpeed: number;
  plSpeedSet2: number;
  enHourlyOutputSet: string; // 理论小时产量入口
  enHourlyOutputReal: string; // 实际小时产量入口
  pickHourlyOutputSet: string; // 理论小时产量酸洗
  pickHourlyOutputReal: string; // 实际小时产量酸洗
  secReason?: string; // 其他异常原因
  outputSe?: number; // 计划秒用时
  outputSeActual?: number; // 实际秒用时
  diff?: number; // 实际-计划秒用时
  type?: string; // 异常区域
}

const allTableData = ref<TableRow[]>([
  {
    id: 0,
    entID: '',
    extID: '',
    steelGrade: '',
    outMatWidth: 0,
    outMatThk: 0,
    outMatWt: '',
    porNo: '',
    shift: '',
    crew: '',
    prodStartTime: '',
    enSpeedAvg: 0,
    enSpeedSet: 0,
    pickSpeed: 0,
    plSpeedSet2: 0,
    enHourlyOutputSet: '',
    enHourlyOutputReal: '',
    pickHourlyOutputSet: '',
    pickHourlyOutputReal: '',
    secReason: '',
    outputSe: 0,
    outputSeActual: 0,
    diff: 0,
    type: '0',
  },
]);

// --- Pagination ---
const pagination = reactive({
  currentPage: 1,
  pageSize: 50,
  total: allTableData.value.length,
});

// 搜索表单数据
const searchForm = reactive({
  entID: '',
  secReason:'',
  timeRange: [],
});

// 弹窗相关的数据
const dialogVisible = ref(false);
const currentCoilNumber = ref('');
const activeView = ref('轧制');
let tempChart: echarts.ECharts | null = null;
let outputChart: echarts.ECharts | null = null;
const tempChartRef = ref(null);
const outChartRef = ref(null);
const outputChartRef = ref(null);
const tempChartSpeed = ref([]);
const outChartSpeed = ref([]);
const outputChartSpeed = ref([]);

const timeData = ref([
  {
    shearActual: '10s',
    shearTheory: '8s',
    waitActual: '15s',
    waitTheory: '12s',
    weldActual: '20s',
    weldTheory: '18s',
    weldingActual: '30s',
    weldingTheory: '25s',
    postWeldActual: '12s',
    postWeldTheory: '10s',
    punchActual: '8s',
    punchTheory: '7s',
    tailShearActual: '10s',
    tailShearTheory: '8s',
    tailWaitActual: '15s',
    tailWaitTheory: '12s',
  },
]);

// 搜索方法
const handleSearch = () => {
  // TODO: 实现搜索逻辑
  pagination.currentPage = 1;
  fetchTableData();
};

// 重置方法
const handleReset = () => {
  searchForm.entID = '';
  searchForm.timeRange = [];
};

// 导出方法
const handleExport = async () => {
  const params = {
    entid: searchForm.entID || '',
    secReason:searchForm.secReason,
    startDate: (searchForm.timeRange && searchForm.timeRange[0]) ? searchForm.timeRange[0] : '',
    endDate: (searchForm.timeRange && searchForm.timeRange[1]) ? searchForm.timeRange[1] : '',
  };
  try {
    await acidRollingApi.exportXlsx(params);
    ElMessage.success('导出成功');
  } catch (error) {
    ElMessage.error('导出失败');
  }
};

// 生命周期钩子
onMounted(() => {
  fetchTableData();
});

// 页码变化
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  fetchTableData();
};
// 分页大小变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  fetchTableData();
};

// 获取表格数据
const fetchTableData = async () => {
  try {
    const params: any = {
      pageIndex: String(pagination.currentPage),
      pageSize: String(pagination.pageSize),
      entid: searchForm.entID,
      secReason:searchForm.secReason,
      startDate: '',
      endDate: '',

    };

    if (searchForm.timeRange && searchForm.timeRange.length === 2) {
      params.startDate = formatDateTime(new Date(searchForm.timeRange[0]), true);
      params.endDate = formatDateTime(new Date(searchForm.timeRange[1]), false);
    }

    // 移除未定义的参数，避免发送空字符串
    Object.keys(params).forEach((key) => {
      if (params[key as keyof typeof params] === undefined) {
        delete params[key as keyof typeof params];
      }
    });

    console.log('Fetching data with params:', params);
    const response = await acidRollingApi.getSingleRollList(params);
    console.log('API Response:', response);

    // Correctly access data from response.data if 'response' is an AxiosResponse
    const responseData = response.data;

    if (responseData && responseData.data && Array.isArray(responseData.data)) {
      console.log('Raw API data:', responseData.data);
      allTableData.value = responseData.data.map((item: any) => {
        console.log('Processing item createTime:', item.createTime, 'type:', typeof item.createTime);
        // 测试时间格式
        if (item.createTime) {
          testDateFormat(item.createTime);
        }
        return {
          ...item, // Keep other original fields if needed for detail view
          type: String(item.type || '0'), // 使用API返回的type值并转换为字符串，如果没有则默认为'0'
        };
      });
      // pickSpeed酸洗实际
      // plSpeedSet2酸洗理论
      // enSpeedSet入口理论
      // enSpeedAvg入口实际
      allTableData.value.forEach((item: TableRow) => {
        item.pickHourlyOutputReal = (item.pickSpeed * 60 * (item.outMatThk / 1000) * (item.outMatWidth / 1000) * 7.8).toFixed(0).toString();
        item.pickHourlyOutputSet = (item.plSpeedSet2 * 60 * (item.outMatThk / 1000) * (item.outMatWidth / 1000) * 7.8).toFixed(0).toString();
        item.enHourlyOutputReal = (item.enSpeedAvg * 60 * (item.outMatThk / 1000) * (item.outMatWidth / 1000) * 7.8).toFixed(0).toString();
        item.enHourlyOutputSet = (item.enSpeedSet * 60 * (item.outMatThk / 1000) * (item.outMatWidth / 1000) * 7.8).toFixed(0).toString();
      });
      pagination.total = responseData.count || responseData.data.length; // Use responseData.count for total
      ElMessage.success(responseData.msg || '查询成功');
    } else {
      ElMessage.info(responseData?.msg || (response as any)?.msg || '未查询到数据或响应格式不正确');
      allTableData.value = [];
      pagination.total = 0;
    }
  } catch (error: any) {
    console.error('获取数据失败:', error);
    // Try to get error message from error.response.data.msg or error.data.msg
    const errorMessage = error.response?.data?.msg || error.data?.msg || error.msg || error.message || '获取数据失败';
    ElMessage.error(errorMessage);
    allTableData.value = [];
    pagination.total = 0;
  }
};

// 新增格式化时间函数
function formatDateTime(date: Date, isStart: boolean = true) {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  return `${y}-${m}-${d} ${isStart ? '00:00:01' : '23:59:59'}`;
}

// 测试时间格式化的辅助函数
function testDateFormat(val: any) {
  console.log('=== Testing date format ===');
  console.log('Input value:', val);
  console.log('Input type:', typeof val);

  if (typeof val === 'string') {
    console.log('String length:', val.length);
    console.log('Contains digits only:', /^\d+$/.test(val));
  }

  // 尝试不同的解析方法
  const methods = [
    { name: 'Direct Date constructor', fn: () => new Date(val) },
    { name: 'ParseInt + Date', fn: () => new Date(parseInt(val)) },
    { name: 'ParseInt * 1000 + Date', fn: () => new Date(parseInt(val) * 1000) },
    { name: 'Number + Date', fn: () => new Date(Number(val)) },
    { name: 'Number * 1000 + Date', fn: () => new Date(Number(val) * 1000) }
  ];

  methods.forEach(method => {
    try {
      const date = method.fn();
      console.log(`${method.name}:`, date.toISOString(), 'Year:', date.getFullYear());
    } catch (error) {
      console.log(`${method.name}: Error -`, error);
    }
  });
  console.log('=== End testing ===');
}





// 显示更多信息
const showMore = async (row: any) => {
  console.log(row)
  currentCoilNumber.value = row.extID;
  dialogVisible.value = true;

  // 先等待弹窗完全打开
  await nextTick();

  // 等待数据加载完成
  await generateLineData(row);

  // 再次等待DOM更新，确保图表容器有正确的尺寸
  await nextTick();

  // 初始化图表，传递当前行数据
  initCharts(row);
};

async function generateLineData(seed: any) {
  try {
    let params = [
      "tcm_entry_speed",
      "tcm_process_speed",
      "tcm_s5_strip_speed_act"
    ]

    const graphParam = {
      line: 'TCM2280',
      extid: [seed.extID],
      curve: params,
    };

    console.log('获取图表数据参数:', graphParam);
    const response = await historyApi.getgraphData(graphParam);
    console.log('图表数据响应:', response);

    if (response && response.data && response.data.data && response.data.data.curve && response.data.data.curve[0]) {
      const curveData = response.data.data.curve[0];
      tempChartSpeed.value = curveData["tcm_entry_speed"] || [];
      outChartSpeed.value = curveData["tcm_s5_strip_speed_act"] || [];
      outputChartSpeed.value = curveData["tcm_process_speed"] || [];

    } else {
      console.warn('图表数据格式不正确或为空');
      tempChartSpeed.value = [];
      outChartSpeed.value = [];
      outputChartSpeed.value = [];
    }
  } catch (error) {
    console.error('获取图表数据失败:', error);
    tempChartSpeed.value = [];
    outChartSpeed.value = [];
    outputChartSpeed.value = [];
  }
};

// 获取效率标签类型
const getEfficiencyType = (value: number) => {
  if (value >= 1) return 'success';
  if (value >= 0.8) return 'warning';
  return 'danger';
};

// 初始化图表
const initCharts = (rowData?: any) => {
  try {
    // 清理之前的图表实例
    if (tempChart) {
      tempChart.dispose();
      tempChart = null;
    }
    if (outputChart) {
      outputChart.dispose();
      outputChart = null;
    }

    // 生成X轴数据（米）
    const generateXAxisData = (dataLength: number) => {
      const xAxisData = [];
      for (let i = 0; i < dataLength; i++) {
        xAxisData.push(i + 1); // 从1米开始
      }
      return xAxisData;
    };

    const commonConfig = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985'
          }
        },
        formatter: function (params: any) {
          const dataIndex = params[0].dataIndex;
          const xValue = params[0].axisValue; // 米数
          const yValue = params[0].value; // 速度值
          return `位置: ${xValue}m<br/>速度: ${yValue} m/min`;
        },
        backgroundColor: 'rgba(0,0,0,0.8)',
        borderColor: '#315070',
        textStyle: {
          color: '#fff'
        }
      },
      grid: {
        left: '5%',
        right: '10%',
        bottom: '10%',
        top: '10%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: [], // 动态生成
        axisLine: { lineStyle: { color: '#315070' } },
        axisLabel: { color: '#7ec7ff' },
        name: '(m)', // 添加单位
        nameTextStyle: { color: '#7ec7ff' },
      },
      yAxis: {
        type: 'value',
        name: '',
        splitLine: { lineStyle: { color: '#315070' } },
        axisLine: { lineStyle: { color: '#315070' } },
        axisLabel: {
          color: '#7ec7ff',
          formatter: function (value: any) {
            return Math.round(value);
          }
        },
      },
      series: [
        {
          data: [],
          type: 'line',
          smooth: true,
          smoothMonotone: 'x',
          lineStyle: {
            color: '#4b9cff',
            width: 2
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(75,156,255,0.3)' },
              { offset: 1, color: 'rgba(75,156,255,0)' },
            ]),
          },
          symbol: 'none',
          symbolSize: 0,
        },
      ],
    };

    // 初始化第一个图表
    if (tempChartRef.value) {
      console.log('初始化第一个图表:', tempChartRef.value);
      tempChart = echarts.init(tempChartRef.value);
      const tempChartOption = JSON.parse(JSON.stringify(commonConfig));

      let chartData = [];
      if (activeView.value === '轧制') {
        tempChartOption.yAxis.name = 'm/min';
        chartData = tempChartSpeed.value || [];

        // 添加设定速度曲线
        if (rowData && rowData.enSpeedSet) {
          // 生成设定速度数据（与实际速度数据长度相同）
          const setSpeedData = Array(chartData.length).fill(rowData.enSpeedSet);

          // 修改tooltip显示多条曲线
          tempChartOption.tooltip.formatter = function (params: any) {
            const xValue = params[0].axisValue; // 米数
            let tooltipContent = `位置: ${xValue}m<br/>`;

            params.forEach((param: any) => {
              if (param.seriesName === '实际速度') {
                tooltipContent += `实际速度: ${Math.round(param.value)} m/min<br/>`;
              } else if (param.seriesName === '设定速度') {
                tooltipContent += `设定速度: ${Math.round(param.value)} m/min<br/>`;
              }
            });

            return tooltipContent;
          };

          // 配置多条曲线
          tempChartOption.series = [
            {
              name: '实际速度',
              data: chartData,
              type: 'line',
              smooth: true,
              smoothMonotone: 'x',
              lineStyle: {
                color: '#4b9cff',
                width: 2
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(75,156,255,0.3)' },
                  { offset: 1, color: 'rgba(75,156,255,0)' },
                ]),
              },
              symbol: 'none',
              symbolSize: 0,
            },
            {
              name: '设定速度',
              data: setSpeedData,
              type: 'line',
              smooth: true,
              smoothMonotone: 'x',
              lineStyle: {
                color: '#52c41a',
                type: 'dashed',
                width: 2
              },
              areaStyle: null,
              symbol: 'none',
              symbolSize: 0,
            }
          ];

          // 添加图例
          tempChartOption.legend = {
            data: ['实际速度', '设定速度'],
            textStyle: { color: '#7ec7ff' },
            top: '5%'
          };

        } else {
          tempChartOption.series[0].data = chartData;
        }
      } else {
        tempChartOption.yAxis.name = 'm/min';
        chartData = [100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600];
        tempChartOption.series[0].data = chartData;
      }

      // 根据数据长度生成X轴
      tempChartOption.xAxis.data = generateXAxisData(chartData.length);

      tempChart.setOption(tempChartOption);
      console.log('第一个图表数据:', tempChartOption.series[0].data);
      console.log('第一个图表X轴:', tempChartOption.xAxis.data);
    }

    // 初始化第一个图表
    if (outChartRef.value) {
      console.log('初始化中间图表:', outChartRef.value);
      tempChart = echarts.init(outChartRef.value);
      const tempChartOption = JSON.parse(JSON.stringify(commonConfig));

      let chartData = [];
      if (activeView.value === '轧制') {
        tempChartOption.yAxis.name = 'm/min';
        chartData = outChartSpeed.value || [];

        // 添加设定速度曲线
        if (rowData && rowData.exSpeedSet) {
          // 生成设定速度数据（与实际速度数据长度相同）
          const setSpeedData = Array(chartData.length).fill(rowData.exSpeedSet);

          // 修改tooltip显示多条曲线
          tempChartOption.tooltip.formatter = function (params: any) {
            const xValue = params[0].axisValue; // 米数
            let tooltipContent = `位置: ${xValue}m<br/>`;

            params.forEach((param: any) => {
              if (param.seriesName === '实际速度') {
                tooltipContent += `实际速度: ${Math.round(param.value)} m/min<br/>`;
              } else if (param.seriesName === '设定速度') {
                tooltipContent += `设定速度: ${Math.round(param.value)} m/min<br/>`;
              }
            });

            return tooltipContent;
          };

          // 配置多条曲线
          tempChartOption.series = [
            {
              name: '实际速度',
              data: chartData,
              type: 'line',
              smooth: true,
              smoothMonotone: 'x',
              lineStyle: {
                color: '#4b9cff',
                width: 2
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(75,156,255,0.3)' },
                  { offset: 1, color: 'rgba(75,156,255,0)' },
                ]),
              },
              symbol: 'none',
              symbolSize: 0,
            },
            {
              name: '设定速度',
              data: setSpeedData,
              type: 'line',
              smooth: true,
              smoothMonotone: 'x',
              lineStyle: {
                color: '#52c41a',
                type: 'dashed',
                width: 2
              },
              areaStyle: null,
              symbol: 'none',
              symbolSize: 0,
            }
          ];

          // 添加图例
          tempChartOption.legend = {
            data: ['实际速度', '设定速度'],
            textStyle: { color: '#7ec7ff' },
            top: '5%'
          };

        } else {
          tempChartOption.series[0].data = chartData;
        }
      } else {
        tempChartOption.yAxis.name = 'm/min';
        chartData = [100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600];
        tempChartOption.series[0].data = chartData;
      }

      // 根据数据长度生成X轴
      tempChartOption.xAxis.data = generateXAxisData(chartData.length);

      tempChart.setOption(tempChartOption);
      console.log('中间图表数据:', tempChartOption.series[0].data);
      console.log('中间图图表X轴:', tempChartOption.xAxis.data);
    }

    // 初始化第二个图表
    if (outputChartRef.value) {
      console.log('初始化第二个图表:', outputChartRef.value);
      outputChart = echarts.init(outputChartRef.value);
      const outputChartOption = JSON.parse(JSON.stringify(commonConfig));

      let chartData = [];
      if (activeView.value === '轧制') {
        outputChartOption.yAxis.name = 'm/min';
        chartData = outputChartSpeed.value || [];

        // 添加工艺设定速度曲线
        if (rowData && rowData.plSpeedSet2) {
          // 生成工艺设定速度数据（与实际速度数据长度相同）
          const setSpeedData = Array(chartData.length).fill(rowData.plSpeedSet2);

          // 修改tooltip显示多条曲线
          outputChartOption.tooltip.formatter = function (params: any) {
            const xValue = params[0].axisValue; // 米数
            let tooltipContent = `位置: ${xValue}m<br/>`;

            params.forEach((param: any) => {
              if (param.seriesName === '实际工艺速度') {
                tooltipContent += `实际工艺速度: ${Math.round(param.value)} m/min<br/>`;
              } else if (param.seriesName === '设定工艺速度') {
                tooltipContent += `设定工艺速度: ${Math.round(param.value)} m/min<br/>`;
              }
            });

            return tooltipContent;
          };

          // 配置多条曲线
          outputChartOption.series = [
            {
              name: '实际工艺速度',
              data: chartData,
              type: 'line',
              smooth: true,
              smoothMonotone: 'x',
              lineStyle: {
                color: '#4b9cff',
                width: 2
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(75,156,255,0.3)' },
                  { offset: 1, color: 'rgba(75,156,255,0)' },
                ]),
              },
              symbol: 'none',
              symbolSize: 0,
            },
            {
              name: '设定工艺速度',
              data: setSpeedData,
              type: 'line',
              smooth: true,
              smoothMonotone: 'x',
              lineStyle: {
                color: '#52c41a',
                type: 'dashed',
                width: 2
              },
              areaStyle: null,
              symbol: 'none',
              symbolSize: 0,
            }
          ];

          // 添加图例
          outputChartOption.legend = {
            data: ['实际工艺速度', '设定工艺速度'],
            textStyle: { color: '#7ec7ff' },
            top: '5%'
          };

        } else {
          outputChartOption.series[0].data = chartData;
        }
      } else {
        outputChartOption.yAxis.name = '℃';
        chartData = [45, 50, 55, 60, 65, 70, 68, 65, 60, 55, 50];
        outputChartOption.series[0].data = chartData;
      }

      // 根据数据长度生成X轴
      outputChartOption.xAxis.data = generateXAxisData(chartData.length);

      outputChart.setOption(outputChartOption);
      console.log('第二个图表数据:', outputChartOption.series[0].data);
      console.log('第二个图表X轴:', outputChartOption.xAxis.data);
    }

    // 强制重新渲染图表
    setTimeout(() => {
      tempChart?.resize();
      outputChart?.resize();
    }, 100);

  } catch (error) {
    console.error('初始化图表失败:', error);
  }
};

// 视图切换处理
const handlechange = (val: string) => {
  activeView.value = val;
  nextTick(() => {
    // 获取当前选中的行数据
    const currentRow = allTableData.value.find(row => row.extID === currentCoilNumber.value);
    initCharts(currentRow);
  });
};

// 弹窗关闭处理
const handleDialogClose = () => {
  // 清理图表实例
  if (tempChart) {
    tempChart.dispose();
    tempChart = null;
  }
  if (outputChart) {
    outputChart.dispose();
    outputChart = null;
  }
  // 清空数据
  tempChartSpeed.value = [];
  outChartSpeed.value = [];
  outputChartSpeed.value = [];
};

// 监听窗口大小变化
window.addEventListener('resize', () => {
  tempChart?.resize();
  outputChart?.resize();
});

const selectRow = async (row: any) => {
  try {
    const params = {
      entId: row.entID,
      extId: row.extID,
      secReason: row.secReason,
      type: row.type,
    };
    await acidRollingApi.saveSingleRoll(params);
    ElMessage.success('保存成功');
    fetchTableData(); // 保存成功后刷新列表
  } catch (error) {
    ElMessage.error('保存失败');
  }
};

// 时间戳格式化方法 - yyyy-MM-dd HH:mm:ss
function formatDate(val: number | string) {
  if (!val) return '-';

  console.log('formatDate input:', val, 'type:', typeof val);

  // 尝试多种解析方法
  const parseAttempts = [
    // 方法1: 直接作为Date构造函数参数
    () => new Date(val),

    // 方法2: 如果是字符串数字，先转换为数字
    () => typeof val === 'string' && /^\d+$/.test(val) ? new Date(parseInt(val)) : null,

    // 方法3: 如果是字符串数字，转换为毫秒级时间戳
    () => typeof val === 'string' && /^\d+$/.test(val) ? new Date(parseInt(val) * 1000) : null,

    // 方法4: 如果是数字，直接使用
    () => typeof val === 'number' ? new Date(val) : null,

    // 方法5: 如果是数字，转换为毫秒级时间戳
    () => typeof val === 'number' ? new Date(val * 1000) : null,
  ];

  let validDate: Date | null = null;

  for (let i = 0; i < parseAttempts.length; i++) {
    try {
      const attempt = parseAttempts[i]();
      if (attempt && !isNaN(attempt.getTime())) {
        const year = attempt.getFullYear();
        // 检查年份是否在合理范围内 (1970-2100)
        if (year >= 1970 && year <= 2100) {
          validDate = attempt;
          console.log(`Method ${i + 1} succeeded:`, attempt.toISOString());
          break;
        } else {
          console.log(`Method ${i + 1} failed: year ${year} out of range`);
        }
      }
    } catch (error) {
      console.log(`Method ${i + 1} failed:`, error);
    }
  }

  if (!validDate) {
    console.log('All parsing methods failed');
    return '-';
  }

  const y = validDate.getFullYear();
  const m = String(validDate.getMonth() + 1).padStart(2, '0');
  const d = String(validDate.getDate()).padStart(2, '0');
  const h = String(validDate.getHours()).padStart(2, '0');
  const min = String(validDate.getMinutes()).padStart(2, '0');
  const s = String(validDate.getSeconds()).padStart(2, '0');

  const result = `${y}-${m}-${d} ${h}:${min}:${s}`;
  console.log('formatDate result:', result);

  return result;
}
</script>

<style scoped>
.single-roll-analysis {
  background-color: #0a1a3a;
  color: #c0c4cc;
  padding: 10px;
  height: 100%;
  /* Use 100% for layout within router-view */
  box-sizing: border-box;
  font-family: 'Microsoft YaHei', 'Segoe UI', sans-serif;
  font-size: 13px;
  overflow: hidden;
  scrollbar-width: thin;
  scrollbar-color: #3a5a8a #142a52;
  display: flex;
  flex-direction: column;
}

.search-form {
  background-color: #1c2d5a;
  padding: 10px 15px;
  border-radius: 3px;
  flex-shrink: 0;
}

:deep(.custom-date-picker.el-date-editor) {
  width: 260px !important;
  /* Match LayOutJudge */
  height: 28px;
  background-color: #0a1a3a;
  border: 1px solid #3a5a8a;
  box-shadow: none;
}

.custom-input,
.custom-select,
.range-input,
:deep(.el-input__wrapper),
:deep(.el-select__wrapper) {
  height: 28px;
  line-height: 28px;
  background-color: #0a1a3a !important;
  border: 1px solid #3a5a8a !important;
  border-radius: 3px !important;
  color: #c0c4cc !important;
  box-shadow: none !important;
  font-size: 13px !important;
}

:deep(.custom-select .el-select__placeholder),
:deep(.custom-select .el-select__caret) {
  color: #c0c4cc;
}

:deep(.el-form-item__label) {
  color: #c0c4cc;
  white-space: nowrap;
  min-width: 65px;
  /* Match LayOutJudge */
  text-align: right;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-tag) {
  width: 60px;
  text-align: center;
}

.table-panel {
  background-color: #1c2d5a;
  padding: 5px;
  border-radius: 3px;
  flex-grow: 1;
  min-height: 0;
  display: flex;
  overflow: hidden;
}

:deep(.el-table),
:deep(.el-table__body),
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper) {
  background-color: #1c2d5a !important;
}

:deep(.el-table__body-wrapper) {
  overflow-x: auto !important;
  overflow-y: auto !important;
  /* 强制滚动条样式 */
  scrollbar-width: 30px !important;
  scrollbar-color: #0000ff #ff0000 !important;
}

:deep(.el-table__header-wrapper) {
  overflow: hidden !important;
}

/* 自定义滚动条样式 - 更宽更明显 */
:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 16px;
  height: 16px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: #1c2d5a !important;
  border-radius: 8px !important;
  border: 2px solid #2a5caa !important;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: #4a5a7a !important;
  border-radius: 8px !important;
  border: 2px solid #1c2d5a !important;
  min-height: 40px !important;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background: #5a6a8a !important;
  border-color: #2a5caa !important;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-corner) {
  background: #1c2d5a !important;
}

:deep(.el-table__empty-block) {
  background: linear-gradient(135deg, #183c7e 0%, #0a1a3a 100%) !important;
}

:deep(.el-table th),
:deep(.el-table td) {
  background-color: #1c2d5a !important;
}

:deep(.el-table__body tr) {
  background-color: #1c2d5a !important;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #223a6b !important;
}

/* --- Pagination Panel (Styles should be consistent) --- */
.pagination-panel {
  background-color: #1c2d5a;
  padding: 8px 15px;
  border-radius: 3px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 0;
}

:deep(.el-pagination) {
  background-color: transparent !important;
}

:deep(.el-pagination__total),
:deep(.el-pagination__sizes),
:deep(.el-pagination__jump),
:deep(.el-pagination__editor),
:deep(.el-pagination button),
:deep(.el-pager li) {
  background-color: #1c2d5a !important;
  color: #7ec7ff !important;
  border: none !important;
}

:deep(.el-pager li.is-active) {
  background-color: #2979ff !important;
  color: #fff !important;
}

.single-roll-analysis>*:not(:last-child) {
  margin-bottom: 15px;
}

:deep(.el-table--border .el-table__inner-wrapper::after),
:deep(.el-table--border::after),
:deep(.el-table--border::before),
:deep(.el-table__border-left-patch),
:deep(.el-table--border .el-table__inner-wrapper::before) {
  z-index: -1;
}

:deep(.el-table td.el-table__cell),
:deep(.el-table th.el-table__cell.is-leaf) {
  border-bottom: 1px solid #06279d !important;
}

:deep(.el-table--border td.el-table__cell),
:deep(.el-table--border th.el-table__cell) {
  border-right: 1px solid #06279d !important;
  border-bottom: none;
}

/* 弹窗相关样式 */
:deep(.efficiency-dialog) {
  background: #0f2142;
  margin-top: 4vh !important;
}

:deep(.efficiency-dialog .el-dialog__header) {
  background: #2a5caa;
  margin: 0;
  padding: 15px 20px;
}

:deep(.efficiency-dialog .el-dialog__title) {
  color: #fff;
  font-size: 16px;
}

:deep(.efficiency-dialog .el-dialog__body) {
  background: #0f2142;
  padding: 20px;
}

.time-data-table {
  margin-bottom: 20px;
}

.charts-container {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.chart-wrapper {
  flex: 1;
  background: #1c2d5a;
  border-radius: 4px;
  padding: 15px;
}

.chart-title {
  color: #7ec7ff;
  font-size: 14px;
  margin-bottom: 10px;
}

.chart {
  height: 300px;
  width: 100%;
}

.switch-buttons {
  margin-top: 20px;
  text-align: center;
}

:deep(.el-radio-button__inner) {
  background: #1c2d5a;
  border-color: #315070;
  color: #7ec7ff;
}

:deep(.el-radio-button__orig-radio:checked + .el-radio-button__inner) {
  background: #2979ff;
  border-color: #2979ff;
  color: #fff;
  box-shadow: -1px 0 0 0 #2979ff;
}

:deep(.el-text) {
  color: #fff !important;
}

.submit-btn {
  background-color: green;
}

.action-btn {
  padding: 3px 8px;
  font-size: 12px;
  border: none;
  border-radius: 3px;
  margin: 0 2px;
  cursor: pointer;
  color: #fff;
}

.ellipsis-cell {
  position: relative;
  display: flex;
  align-items: center;
  min-height: 28px;
}

.ellipsis-text {
  display: inline-block;
  max-width: 170px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  vertical-align: middle;
  background: #fff;
  color: #333;
  border-radius: 3px;
  padding: 2px 6px;
  min-height: 28px;
  width: 100%;
}

.expand-btn {
  color: #409eff;
  cursor: pointer;
  margin-left: 6px;
  font-size: 12px;
  user-select: none;
  white-space: nowrap;
}

.ellipsis-input {
  flex: 1;
  min-width: 0;
}

.ellipsis-input.ellipsis-single textarea {
  overflow: hidden !important;
  white-space: nowrap !important;
  text-overflow: ellipsis !important;
  resize: none;
}

/* 表格滚动条样式 - 强制加宽 */
:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 30px !important;
  height: 30px !important;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: #ff0000 !important;
  border-radius: 15px !important;
  border: 5px solid #00ff00 !important;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: #0000ff !important;
  border-radius: 15px !important;
  border: 5px solid #ffff00 !important;
  min-height: 80px !important;
  min-width: 80px !important;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background: #ff00ff !important;
  border-color: #00ffff !important;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-corner) {
  background: #ff0000 !important;
}

/* 垂直滚动条 */
:deep(.el-table__body-wrapper::-webkit-scrollbar:vertical) {
  width: 30px !important;
}

/* 水平滚动条 */
:deep(.el-table__body-wrapper::-webkit-scrollbar:horizontal) {
  height: 30px !important;
}

/* 全局滚动条样式 - 更宽更明显 */
::-webkit-scrollbar {
  width: 20px !important;
  height: 20px !important;
}

::-webkit-scrollbar-track {
  background: #1c2d5a !important;
  border-radius: 10px !important;
  border: 3px solid #2a5caa !important;
}

::-webkit-scrollbar-thumb {
  background: #4a5a7a !important;
  border-radius: 10px !important;
  border: 3px solid #1c2d5a !important;
  min-height: 50px !important;
  min-width: 50px !important;
}

::-webkit-scrollbar-thumb:hover {
  background: #5a6a8a !important;
  border-color: #2a5caa !important;
}

::-webkit-scrollbar-corner {
  background: #1c2d5a !important;
}
</style>
